package com.smooth.mall.filter;

import com.smooth.mall.common.Constant;
import com.smooth.mall.model.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class UserFilter implements Filter {
    //设置全局静态变量，保存当前用户信息
    public static User currentUser;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain
            filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        currentUser = (User)session.getAttribute(Constant.SMOOTH_MALL_USER);
        if(currentUser==null){
            //return ApiRestResponse.error(SmoothMallExceptionEnum.NEED_LOGIN);
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)
            servletResponse).getWriter();
            out.write("{\n" +
                    " \"status\": 10007,\n" +
                    " \"msg\": \"NEED_LOGIN\",\n" +
                    " \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            return;//出错情况下，直接过滤，过滤器不往下执行
        }
        //校验成功，放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

}
